	var displayLang;
	var etype ;
	var eid;
	var genre ;
	var vid ;
	var gid;
	var viewLang ;
	var transerv;
	var transVid;
	var STATUS_CONFLICT = "conflict";
	var STATUS_REMOVE = "removed";
	var STATUS_SRC_REMOVE = "src_removed";
	var STATUS_NOAUTHORITY = "noauthority";
	var STATUS_OK="ok";
	var STATUS_HasTransView = "hasTrans";
	var nameMaxLength = 60;
$(function(){
/*START of init*/
	//global variables
	transerv = WEBAPP+"translate";
	displayLang = $("#display-lang").val();
	etype = parseInt($("#etype").val());
	eid = parseInt($("#eid").val());
	genre = $("#genre").val();
	vid = $("#vid").val();
	gid =$("#gid").val();
	transVid = $("#tvid").val();
	viewLang = $("#objLang option:selected").val();
	checkContentLength($(".nameBox .originTitle"),nameMaxLength);
	
	/*disable language setting during the view editing*/
	$("#set-option").unbind("click");
	
	//init the data item titlebars and their values
	init();
/*END of init*/	
	
	$("#viewName").focus(function(){
	    	$(this).parent().find(".error").remove();
	});
	
	$(".dmList .titlebar").live("click",function(){
		$(this).find("a.status").toggleClass("collapse");
		$(this).parent().find(".content").toggle('fast');
	});
	
	$(".edit-save .sbutton").click(function(){
		//check if any of data item  has error msg
		if($(".error").length>0)
			return false;
		//check if any of data item names is empty
		var flag = false;
		$(".titlebar .ftext").each(function(){
			if(isEmpty($(this))){
				flag = true;
				var span = $("<span class='error'></span>");
	    		if(displayLang=="en"){
	    			span.text("Please enter a name");
	    		}else if(displayLang=="zh"){
	    			span.text("请输入名称");
	    		}
	    		$(this).parent().find(".originTitle").append(span);
				return;
			}
		});
		if(flag)
			return false;
		//check if the view name is empty
		if(isEmpty($("#viewName"))){
			var span = $("<span class='error'></span>");
    		if(displayLang=="en"){
    			span.text("Please enter a name");
    		}else if(displayLang=="zh"){
    			span.text("请输入名称");
    		}
    		$("#viewName").parent().find(".originTitle").append(span);
			return false;
		}
		
		var viewname =$("#viewName").val().trim();
		//check if the view name has conflict
		var originTitleSpan = $(".nameBox .originTitle");
        var result = storeTranslatedView(viewname);
        var status = result["status"];
        if(status ==STATUS_CONFLICT){
        	var span = $("<span class='error'></span>");
    		if(displayLang=="en"){
    			span.text("The name has existed");
    		}else if(displayLang=="zh"){
    			span.text("名称已经存在");
    		}
    		originTitleSpan.after(span);
        	return;
        }
        else if(status ==STATUS_REMOVE){
        	if(displayLang=="en"){
 				$.messager.alert('Error','Sorry. The translated view has been removed elsewhere!','error',function(){
 					var location = getEntityLinkHref(genre,eid,displayLang);
 		    		window.location = location;
 				});
 			}else if(displayLang=="zh"){
 				$.messager.alert('错误','抱歉，该翻译的视图已在别处被删除!','error',function(){
 					var location = getEntityLinkHref(genre,eid,displayLang);
 		    		window.location = location;
 				});
 			}
 			return ;
        }
        else if(status ==STATUS_HasTransView){
        	var warning = $(".warning");
        	var transvid = result["transvid"];
        	var location = "/sview/views/translate.jsp?genre="+genre+"&eid="+eid
        	             +"&vid="+vid+"&lang="+displayLang;
        	warning.find(".translink").attr("href",location);
    		if (displayLang == "en") {
    			dialog_title = "Info";
    		} else if (displayLang == "zh") {
    			dialog_title = "提示";
    		}
    		warning.dialog({
    			title : dialog_title,
   			    modal:true,
   			    width:500
   		    });
    		
 			return ;
        }else if(status ==STATUS_SRC_REMOVE){
        	if(displayLang=="en"){
 				$.messager.alert('Error','Sorry. The source view of this translated view has been removed elsewhere!','error',function(){
 					var location = getEntityLinkHref(genre,eid,displayLang);
 		    		window.location = location;
 				});
 			}else if(displayLang=="zh"){
 				$.messager.alert('错误','抱歉，该翻译的视图已在别处被删除!','error',function(){
 					var location = getEntityLinkHref(genre,eid,displayLang);
 		    		window.location = location;
 				});
 			}
 			return ;
        }
        else if(status ==STATUS_NOAUTHORITY ){
        	if(displayLang=="en"){
				$.messager.alert('Info','The translated view is being edited elsewhere. Please retry later!','info');
			}else if(displayLang=="zh"){
				$.messager.alert('提示','翻译的视图正在别处被编辑。请稍后再试!','info');
			}
			return ;
        }else if(status==STATUS_OK){
    		var location = getEntityLinkHref(genre,eid,displayLang);
    		window.location = location;
        }
        
	});
	
	$(".edit-save .cbutton").click(function(){
		var location = getEntityLinkHref(genre,eid,displayLang);
		window.location = location;
	});

});

function init(){
	if($("a.showoutdate").length>0){
		$("a.showoutdate").live("click",function(){
			$(this).parent().toggleClass("down");
			$(this).parent().find("ul").toggle();
		});
	}
	//init the data item titlebars and their values
	initViewDM(vid,transVid);
}

//init the data item titlebars and their values
function initViewDM(vid,tvid){
	 var data={};
	 data["vid"] = vid;
	 data["tvid"] = tvid;
	 data =  JSON.stringify(data);
	 data =("transViewInit="+encodeURIComponent(data));
	 
	 $.ajax({
		   url:transerv,
	   	   async:false,
	   	   data:data,
	   	   dataType:"json",
	   	   type:"post",
		   success: function( result ) {
			    var data = result.items;
			    var removed = result.removed;
			    var liArray = new Array();
				for(i=0;i<data.length;i++){
					var item = data[i];
					var dmtype = item.dmtype;
					var dmid = item.dmid;
					var inverse = item.inverse;
					var name = item.name;
					var vtype = item.vtype;
					var arity = item.arity;
					var funct = item.functional;
					var isAdded = item["isAdded"];
					var originStr = item["originStr"];
					var box = $(".dmList");
					var li = addDM(box,false,dmtype,dmid,arity,inverse,vtype,funct,name,isAdded,originStr);
					liArray.push(li) ;
				}
				
				if(removed.length>0){
					$(".ot").show();
				}
				for(i=0;i<removed.length;i++){
					var item = removed[i];
					var dmtype = item.dmtype;
					var dmid = item.dmid;
					var inverse = item.inverse;
					var name = item.name;
					var vtype = item.vtype;
					var arity = item.arity;
					var funct = item.functional;
					var isAdded = false;
					var originStr = item["originStr"];
					var box = $(".rmList");
					var li = addDM(box,true,dmtype,dmid,arity,inverse,vtype,funct,name,isAdded,originStr);
					liArray.push(li) ;
				}
				
			   	/*must be out of the above loop
			   	 * because the above loop has timeout function
			   	 * */
			   	for(i=0;i<liArray.length;i++){
			   		var li  =  liArray[i] ;
			   		var pvalue =li.find(".pvalue");
			   		var liContainer = li.find(".li-container");
			   		var dmtype = parseInt(liContainer.attr("dmtype"));
			   		var dmid = parseInt(liContainer.attr("dmid"));
			   		var inverse  = parseInt(liContainer.attr("inverse")) ;
			   		var status = "undownloaded" ;
			   		fetchValues(displayLang,pvalue,dmtype,dmid,inverse,genre,eid,status);
			   	}
		   }
	 });
}

function addDM(box,isoutdated,dmtype,dmid,arity,inverse,vtype,funct,name,isAdded,originStr){
	var li = $("<li class='prop'></li>");
	box.append(li);
	var div  = $("<div class='li-container'></div>");
	li.append(div);
	div.attr("inverse",inverse);
	div.attr("vtype",vtype) ;
	div.attr("dmtype",dmtype);
	div.attr("dmid",dmid) ;
	div.attr("arity",arity);
	div.attr("funct",funct);
	
    var titleDiv = $("<div class='titlebar'></div>");
    div.append(titleDiv);
    var spanLoading = $("<span class='loading'></span>");
    titleDiv.append(spanLoading);
    addExpandButtonToBar(titleDiv);
    
    if(!isoutdated){
       //对于非过期的query item
      var input = $("<input class='ftext' type='text' />");
      titleDiv.append(input) ;
      if(isAdded==false){
    	input.val(originStr);
      }
      /*bind validate function*/
      input.focus(function(event){
    	$(this).parent().find(".error").remove();
    	event.stopPropagation();
      });
      input.click(function(event){
    	event.stopPropagation();
      });
      input.blur(function(){
    	if(isEmpty(this)){
    		var span = $("<span class='error'></span>");
    		if(displayLang=="en"){
    			span.text("Please enter a name");
    		}else if(displayLang=="zh"){
    			span.text("请输入名称");
    		}
    		$(this).parent().find(".originTitle").append(span);
    	}else{
    		   var name = $(this).val().trim();
    		   var liContainer = $(this).parent().parent();
    		   var dmtype = liContainer.attr("dmtype") ;
    		   var dmid = liContainer.attr("dmid");
    		   var inverse = liContainer.attr("inverse");
    		   var originTitleSpan =  $(this).parent().find(".originTitle");
    	}
      });
    
      var span = $("<span class='originTitle'></span>");
      name = cutText(name,nameMaxLength);
      span.text(name);
      titleDiv.append(span);
    }else{
    	var input = $("<input class='ftext' type='text' disabled/>");
        titleDiv.append(input) ;
        if(isAdded==false){
        	input.val(originStr);
        }
    }
    
    var content = $("<div class='content'></div>");
	var pvalue = $("<ul class='pvalue'></ul>");
    div.append(content) ;
	content.append(pvalue);

    var status = "undownloaded" ;
    
	return li;
}

function addExpandButtonToBar(bar){
	var button = $('<a class="status"></a>');
	bar.append(button);
}

/**
 * 翻译的view的名称如果已经存在，但是它也是原有view同一个类别下的，那么
 * 提示是否覆盖，否则
 * 显示名称冲突
 * @param vid
 * @returns 1:继续执行，0：返回，2：询问
 */
function checkViewNameConflict(originTitleSpan,name,groupID,vid,transVid){
	var flag = 1 ;
	var data={};
	data["name"] = name;
	data["groupID"] = groupID;
	data["viewID"] = vid;
	data["translatedViewID"] = transVid;
	data["userName"] = getUser();
    data =  JSON.stringify(data);
    data =("checkViewNameConflict="+encodeURIComponent(data));
    $.ajax({
    	url:transerv,
     	async:false,
     	data:data,
     	dataType:"text",
     	type:"post",
        success:function(result){
        	if(result=="conflict"){
        		var span = $("<span class='error'></span>");
        		if(displayLang=="en"){
        			span.text("The name has existed");
        		}else if(displayLang=="zh"){
        			span.text("名称已经存在");
        		}
        		originTitleSpan.after(span);
        		flag = 0;
        	}else if(result=="ask"){
                flag = 2;
        	}
         }
    });
    
    return flag;
}

function isEmpty(input){
	if($(input).val().trim()=="")
		return true;
	return false;
}

function storeTranslatedView(viewname){
    var result; 

    var user = getUser();
   //save the query items
    var dmArray = new Array();
	$(".vcontent .titlebar .ftext").each(function(){
		var liContainer = $(this).parent().parent();
		var name = $(this).val().trim();
		var json = new Object();
		json["label"] = name;
		var dmtype = liContainer.attr("dmtype") ;
		var dmid = liContainer.attr("dmid");
		var inverse = liContainer.attr("inverse");
		json["dmtype"]=dmtype;
		json["dmid"]=dmid;
		json["inverse"]=inverse;
		dmArray.push(json);
	});
	
	var data={};
	data["name"] = viewname;
	data["groupID"] = gid;
	data["viewID"] = vid;
	data["translatedViewID"] = transVid;
	data["userName"] = getUser();
	data["viewLang"] = viewLang;
	data["dmNames"] = dmArray;
	data =  JSON.stringify(data);
	data = ("storetransview="+encodeURIComponent(data));
	 
	 $.ajax({
	   	  url:transerv,
	   	  async:false,
	   	  data:data,
	   	  dataType:"json",
	   	  type:"post",
	   	  beforeSend:function(){
	   		  var div = $("<div class='load-data2'></div>");
	   		  $("body").append(div);
	   	  },
	   	  success:function(json){
	   		  $("body").find(".load-data2").remove();
	   		  result = json;
	   	  }
     });
	 
	 return result;
}



